package com.company.algo.DP.subseqProblem.editDistance;

/**583. 两个字符串的删除操作
 abc abcb -> 1
 abcd abcb-> 2
 ab ac -> 2
 给定两个单词 word1 和 word2，找到使得 word1 和 word2 相同所需的最小步数，每步可以删除任意一个字符串中的一个字符。
 dp[i][j]为使得word1以i-1结尾和word2以j-1结尾的字符串相同所需的最小操作步数
 dp[i][j]=
    1. word1[i]==word2[j],无需新的操作,dp[i-1][j-1]
    2. word1[i]!=word2[j],
        2.1 删除word1[i],dp[i-1][j]+1
        2.2 删除word2[j],dp[i][j-1]+1
        故dp[i][j] = Math.min(dp[i-1][j]+dp[i][j-1])+1
 dp[0][0] = 0,
 dp[0][j] = j;
 dp[i][0] = i;
 */
public class deleteFor2Strings {
    public int minDistance(String word1, String word2) {
        int m = word1.length();
        int n = word2.length();
        int[][] dp = new int[m+1][n+1];
        for(int i=0; i<=m; i++) dp[i][0] = i;
        for(int j=1; j<=n; j++) dp[0][j] = j;
        for (int i = 1; i <=m ; i++) {
            for (int j = 1; j <=n ; j++) {
                if (word1.charAt(i-1)==word2.charAt(j-1)) dp[i][j] = dp[i-1][j-1];
                else dp[i][j] = Math.min(dp[i-1][j],dp[i][j-1])+1;
            }
        }
        return dp[m][n];
    }
}
